package com.jiazhong.mingxing.boot.boot04.test;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@SpringBootTest
@Slf4j
public class HashApp {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void a() {
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        forHash.put("A", "a", "aa");
        forHash.put("A", "b", "bb");
        forHash.put("A", "c", "1");
        forHash.put("A", "d", "1.6");
        Map<Object, Object> map = new HashMap<>();
        map.put("e", "ee");
        map.put("f", "ff");
        map.put("g", "gg");
        forHash.putAll("A", map);
        // 存在没效果，不存在就添加
        forHash.putIfAbsent("A", "b", "bb2");
        forHash.putIfAbsent("A", "h", "hh");
    }

    @Test
    public void b() {
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        // 获取到所有内容
        Map<Object, Object> all = forHash.entries("A");
        log.info("all:{}", all);
        // 获取到某一个
        Object c = forHash.get("A", "c");
        Object a = forHash.get("A", "a");
        Object m = forHash.get("A", "m");
        log.info("c:{},a:{},m:{}", c, a, m);
        // 获取到所有的key
        Set<Object> keys = forHash.keys("A");
        // 获取到所有值
        List<Object> values = forHash.values("A");
        log.info("keys:{}", keys);
        log.info("values:{}", values);
        // 随机获取一个key
        Object randomKey = forHash.randomKey("A");
        // 随机获取多个key
        List<Object> randomKeys = forHash.randomKeys("A", 3);
        log.info("randomKey:{}", randomKey);
        log.info("randomKeys:{}", randomKeys);
        // 随机获取一个k-v
        Map.Entry<Object, Object> randomEntry = forHash.randomEntry("A");
        log.info("randomEntry:{}", randomEntry);
        Map<Object, Object> randomEntries = forHash.randomEntries("A", 2);
        log.info("randomEntries:{}", randomEntries);
    }

    @Test
    public void c() {
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        // 删除指定的key
        forHash.delete("A", "e", "m");
        // 判断是否存在这个key
        Boolean hasKey = forHash.hasKey("A", "a");
        log.info("hasKey:{}", hasKey);
        // 数值运算
        forHash.increment("A", "c", 1);
        forHash.increment("A", "c", -6);
        forHash.increment("A", "d", 1.7);

    }
}
